# Created by: MasteR
# Rewritten by: L2EmuProject
import sys
from com.l2emu.gameserver.model.quest 			   import State
from com.l2emu.gameserver.model.quest 			   import QuestState
from com.l2emu.gameserver.datatables 			   import NpcTable
from com.l2emu.gameserver.templates.chars 		   import L2NpcTemplate
from com.l2emu.gameserver.model.actor.instance	   import L2PcInstance
from com.l2emu.gameserver.datatables   		       import SpawnTable
from com.l2emu.gameserver.datatables			   import ItemTable
from com.l2emu.gameserver.network.serverpackets	   import RadarControl
from com.l2emu 					                   import L2DatabaseFactory
from com.l2emu.gameserver.model.quest.jython 	   import QuestJython as JQuest

from java.util 		                        	   import Iterator
from com.l2emu                               	   import Config

qn = "8003_Search"

NPC = [50000]
		
MOBS = ["L2Boss","L2Chest","L2FeedableBeast","L2Minion","L2Monster","L2QuestMonster","L2RaidBoss","L2RiftInvader","L2SepulcherMonster","L2TamedBeast"]


class Quest (JQuest) :

	def __init__(self,id,name,descr): JQuest.__init__(self,id,name,descr)

	def onAdvEvent (self,event,npc,player) :

		def message (text) :
			return L2PcInstance.sendMessage (player, text)

	#main sub begin
		htmltext = "search.htm"
		title = "<html><title>Drop Calculator</title><body>"
		st = player.getQuestState(qn)
		if not st: return htmltext
 
		if st.getQuestItemsCount(57) < 0: 
			message ("You not have enought adena for payment this service.")
			return
		st.takeItems(57,0)

		text = "search.htm"
		search_by = ''
		param = ''
		page = ''
		inputs = event.split (' ')
		length = len(inputs)
		if length < 3: return htmltext
		search_by = inputs[0]
		#get input data
		if search_by == "m":
			x = int(inputs[1])
			y = int(inputs[2])
			z = int(inputs[3])
		else:
			if inputs[1].isdigit():
				page = int(inputs[1])
			else:
				message ("Incorrect search name!")
				return htmltext
			for i in range(2,length):
				param += inputs[i] + " "
			param = param.strip()

		#find by level
		if search_by == "l" :
			if param.isdigit():
				level = int(param)
				if not (level > 0 and level < 100): 
					return "Please enter level between 1 and 99."
				npcData = []
				for t in NpcTable.getInstance().getAllTemplates().values():
					if  t.getLevel() == level:
						npcData.append(t)
				if npcData:
					length = len(npcData)
					maxPerPage = 15
					maxPages = int(length / maxPerPage)
					if length > maxPerPage * maxPages: maxPages = maxPages + 1
					if page > maxPages: page = maxPages
					start = maxPerPage * page
					end = length
					if (end - start) > maxPerPage: end = start + maxPerPage
					text = title
					text += "<table width=260><tr>"
					if page == 0:
						text += "<td width=40><button value=\"Back\" action=\"bypass -h Quest 8003_Search\" width=40 height=15 back=\"L2UI_ct1.button_df\" fore=\"L2UI_ct1.button_df\"></td>"
					else :
						text += "<td width=40><button value=\"Back\" action=\"bypass -h Quest 8003_Search l "+ str(page-1) + " " + str(level) + "\" width=40 height=15 back=\"L2UI_ct1.button_df\" fore=\"L2UI_ct1.button_df\"></td>"
					text += "<td width=180><center><a action=\"bypass -h Quest 8003_Search\">Search Result by Level</a><br>Lvl:" + str(level) + " Found:" + str(length) + " Page:" + str(page+1)+ "/" + str(maxPages) +"</center></td>"
					if (page + 1) < maxPages:
						text += "<td width=40><button value=\"Next\" action=\"bypass -h Quest 8003_Search l "+ str(page+1) + " " + str(level) + "\" width=40 height=15 back=\"L2UI_ct1.button_df\" fore=\"L2UI_ct1.button_df\"></td>"
					else :
						text += "<td width=40></td>"
					text += "</tr></table>"
					text += "<table width=\"100%\">"
					text += "<tr><td><font color=\"LEVEL\">Name</font></td><td width=70><font color=\"LEVEL\">Drop&Spoil</font></td></tr>"
					for i in range(start,end):
						intagro = npcData[i].getAggroRange()
						if intagro > 0: agro = "<font color=\"LEVEL\">*</font>" 
						else: agro = " "
						name = npcData[i].getName()
						if name == '' or name == ' ' or name == '   ':
							name = "noname"
						text += "<tr><td><a action=\"bypass -h Quest 8003_Search s 0 " + str(npcData[i].getNpcId()) + "\">" + name + "</a>" + agro + "</td>"
						if npcData[i].getType() in MOBS:
							text += "<td><center><button value=\"Show\" action=\"bypass -h Quest 8003_Search d 0 " + str(npcData[i].getNpcId()) + "\" width=40 height=15 back=\"L2UI_ct1.button_df\" fore=\"L2UI_ct1.button_df\"></center></td>"
						else:
							text += "<td></td>"
						text += "</tr>"
					text += "</table>"
					text += "</body></html>"
					return text
				else:
					message ("Not found NPC level " + str(level) + ".")
			else:
				message ("Please enter number in 1 to 99")
		#find by name
		if search_by == "n" :
			count = len(param)
			if count > 3:
				name = param.replace('_',' ')
				npcData = []
				for t in NpcTable.getInstance().getAllTemplates().values():
					if name.lower() in t.getName().lower():
						npcData.append(t)
				if npcData:
					length = len(npcData)
					maxPerPage = 15
					maxPages = int(length / maxPerPage)
					if length > maxPerPage * maxPages: maxPages = maxPages + 1
					if page > maxPages: page = maxPages
					start = maxPerPage * page
					end = length
					if (end - start) > maxPerPage: end = start + maxPerPage
					text = title
					text += "<table width=260><tr>"
					if page == 0:
						text += "<td width=40><button value=\"Back\" action=\"bypass -h Quest 8003_Search\" width=40 height=15 back=\"L2UI_ct1.button_df\" fore=\"L2UI_ct1.button_df\"></td>"
					else :
						text += "<td width=40><button value=\"Back\" action=\"bypass -h Quest 8003_Search n "+ str(page-1) + " " + str(name) + "\" width=40 height=15 back=\"L2UI_ct1.button_df\" fore=\"L2UI_ct1.button_df\"></td>"
					text += "<td width=180><center><a action=\"bypass -h Quest 8003_Search\">Search Result by Level</a><br>Name:" + str(name) + " Found:" + str(length) + " Page:" + str(page+1)+ "/" + str(maxPages) +"</center></td>"
					if (page + 1) < maxPages:
						text += "<td width=40><button value=\"Next\" action=\"bypass -h Quest 8003_Search n "+ str(page+1) + " " + str(name) + "\" width=40 height=15 back=\"L2UI_ct1.button_df\" fore=\"L2UI_ct1.button_df\"></td>"
					else :
						text += "<td width=40></td>"
					text += "</tr></table>"
					text += "<table width=\"100%\">"
					text += "<tr><td><font color=\"LEVEL\">Name</font></td><td><font color=\"LEVEL\">Level</font></td><td width=60><font color=\"LEVEL\">Drop&Spoil</font></td></tr>"
					for i in range(start,end):
						intagro = npcData[i].getAggroRange()
						if intagro > 0: agro = "<font color=\"LEVEL\">*</font>" 
						else: agro = " "
						text += "<tr><td><a action=\"bypass -h Quest 8003_Search s 0 " + str(npcData[i].getNpcId()) + "\">" + npcData[i].getName() + "</a></td>" + "<td>" + str(npcData[i].getLevel()) + agro + "</td>"
						text += "<td><center><button value=\"Show\" action=\"bypass -h Quest 8003_Search d 0 " + str(npcData[i].getNpcId()) + "\" width=40 height=15 back=\"L2UI_ct1.button_df\" fore=\"L2UI_ct1.button_df\"></center></td></tr>"
					text += "</table>"
					text += "</body></html>"
					return text
				else:
					message ("Not found NPC name " + str(name) + ".")
			else:
				message ("Please enter 4 or more chars!")

		#show spawns for ID
		if search_by == "s" :
			id = int(param)
			text = ''
			SpawnData = []
			npcData = NpcTable.getInstance().getTemplate(id)
			for t in SpawnTable.getInstance().getSpawnTable().values():
				if  t.getNpcId() == id:
					SpawnData.append(t)
			if SpawnData:
				length = len(SpawnData)
				maxPerPage = 15
				maxPages = int(length / maxPerPage)
				if length > maxPerPage * maxPages: maxPages = maxPages + 1
				if page > maxPages: page = maxPages
				start = maxPerPage * page
				end = length
				if (end - start) > maxPerPage: end = start + maxPerPage
				intagro = npcData.getAggroRange()
				if intagro > 0: agro = "<font color=\"LEVEL\">*</font>" 
				else: agro = " "
				text = title
				text += "<table width=260><tr>"
				if page == 0:
					text += "<td width=40><button value=\"Back\" action=\"bypass -h Quest 8003_Search l 0 " + str(npcData.getLevel()) + "\" width=40 height=15 back=\"L2UI_ct1.button_df\" fore=\"L2UI_ct1.button_df\"></td>"
				else :
					text += "<td width=40><button value=\"Back\" action=\"bypass -h Quest 8003_Search s "+ str(page-1) + " " + str(id) + "\" width=40 height=15 back=\"L2UI_ct1.button_df\" fore=\"L2UI_ct1.button_df\"></td>"
				text += "<td width=180><center><a action=\"bypass -h Quest 8003_Search\">Spawns Search Result</a></center></td>"
				if (page + 1) < maxPages:
					text += "<td width=40><button value=\"Next\" action=\"bypass -h Quest 8003_Search s "+ str(page+1) + " " + str(id) + "\" width=40 height=15 back=\"L2UI_ct1.button_df\" fore=\"L2UI_ct1.button_df\"></td>"
				else :
					text += "<td width=40></td>"
				text += "</tr></table>"
				text += "<center><font color=\"LEVEL\">Level " + str(npcData.getLevel()) + " - " + str(npcData.getName()) + agro + "</font><br>"
				text += "Found:" + str(length) + " Page:" + str(page+1)+ "/" + str(maxPages) +"</center>"
				text += "<table width=\"100%\">"
				text += "<tr><td><center><font color=\"LEVEL\">X         Y         Z</font></center></td></tr>"
				for i in range(start,end):
					xyz = str(SpawnData[i].getLocx()) + " " + str(SpawnData[i].getLocy()) + " " + str(SpawnData[i].getLocz())
					text += "<tr><td><center><a action=\"bypass -h Quest 8003_Search m " + xyz + "\">" + xyz + "</center></td></tr>"
				text += "</table>"
				text += "</body></html>"
				return text
			else:
				message ("Not found spawn for level " + str(npcData.getLevel()) + " - " + npcData.getName() + ".")

		#show Radar
		if search_by == "m" :
			st.addRadar(x,y,z)
			return
	
		# drop and spoil show
		if search_by == "d":
			id = int(param)
			DropData = []
			SweepData = []
			npcData = NpcTable.getInstance().getTemplate(id)
			intagro = npcData.getAggroRange()
			if intagro > 0: agro = "<font color=\"LEVEL\">*</font>" 
			else: agro = " "
			if npcData.getDropData():
				for cat in npcData.getDropData():
					for drop in cat.getAllDrops():
						DropData.append(drop)
						SweepData.append(cat)
				if DropData:
					length = len(DropData)
					maxPerPage = 15
					maxPages = int(length / maxPerPage)
					if length > maxPerPage * maxPages: maxPages = maxPages + 1
					if page > maxPages: page = maxPages
					start = maxPerPage * page
					end = length
					if (end - start) > maxPerPage: end = start + maxPerPage
					text = title
					text += "<table width=260><tr>"
					if page == 0:
						text += "<td width=40><button value=\"Back\" action=\"bypass -h Quest 8003_Search l 0 " + str(npcData.getLevel()) + "\" width=40 height=15 back=\"L2UI_ct1.button_df\" fore=\"L2UI_ct1.button_df\"></td>"
					else :
						text += "<td width=40><button value=\"Back\" action=\"bypass -h Quest 8003_Search d "+ str(page-1) + " " + str(id) + "\" width=40 height=15 back=\"L2UI_ct1.button_df\" fore=\"L2UI_ct1.button_df\"></td>"
					text += "<td width=180><center><a action=\"bypass -h Quest 8003_Search\">Drop and Spoil Result</a></center></td>"
					if (page + 1) < maxPages:
						text += "<td width=40><button value=\"Next\" action=\"bypass -h Quest 8003_Search d "+ str(page+1) + " " + str(id) + "\" width=40 height=15 back=\"L2UI_ct1.button_df\" fore=\"L2UI_ct1.button_df\"></td>"
					else :
						text += "<td width=40></td>"
					text += "</tr></table>"
					text += "<center><font color=\"LEVEL\">Level " + str(npcData.getLevel()) + " - " + str(npcData.getName()) + agro + "</font><br>"
					text += "Found:" + str(length) + " Page:" + str(page+1)+ "/" + str(maxPages) +"</center>"
					text += "<table width=260>"
					i = 0
					for i in range(start,end):
						itemname = ItemTable.getInstance().getTemplate(DropData[i].getItemId()).getName()
						type = ""
						if DropData[i].isQuestDrop(): 
							type = "Qu"
						if SweepData[i].isSweep(): 
							type = "<font color=\"LEVEL\">Sw</font>" 
						else:
							type = ""
						text += "<tr>"
						text += "<td width=\"100%\">" + itemname + "</td>"
						text += "<td width=35>" + type + "</td>"
						text += "<td width=90>" + str(float(DropData[i].getChance()) / 10000 * Config.RATE_DROP_ITEMS) + "%</td>"
						text += "</tr>"
					text += "</table>"
					text += "</body></html>"
			else:
				message ("Not found drop and spoil data for Level " + str(npcData.getLevel()) + " - " + str(npcData.getName()))
			return text
		#search by item_id
		if search_by == "i" :
			aMobID = []
			aMobName = []
			aMobLevel = []
			aMobAggro = []
			aMobType = []
			aChance = []
			aCategory = []
			item_id = int(param)
			found = 0
			for itemtype in (['armor','weapon','etcitem','custom_armor','custom_weapon','custom_etcitem']):
				query = "select name from " + itemtype + " where item_id = " + str(item_id) + " LIMIT 1"
				con1=L2DatabaseFactory.getInstance().getConnection()
				stmt1=con1.prepareStatement(query)
				rs1=stmt1.executeQuery()
				if rs1.next() :
					name = rs1.getString("name")
				con1.close()
			# HTML CODE
			text = title
			con2=L2DatabaseFactory.getInstance().getConnection()
			query = "select icon from icons where item_id = " + str(item_id) + " LIMIT 1"
			stmt2=con2.prepareStatement(query)
			rs2=stmt2.executeQuery()
			if rs2.next():
				icon = rs2.getString("icon")
			else:
				icon = "none"
			con2.close()
			con2=L2DatabaseFactory.getInstance().getConnection()
			query = "select droplist.category, droplist.chance, npc.id, npc.name, npc.level, npc.aggro, npc.type "
			query += "from droplist inner join npc ON (droplist.mobId = npc.id) where itemid = " 
			query += str(item_id) + " ORDER BY category, chance DESC LIMIT 30"
			stmt2=con2.prepareStatement(query)
			rs2=stmt2.executeQuery()
			if rs2 :
				while (rs2.next()):
						found = 1
						aCategory.append(rs2.getInt("droplist.category"))
						aChance.append(rs2.getInt("droplist.chance"))
						aMobID.append(rs2.getInt("npc.id"))
						aMobName.append(rs2.getString("npc.name"))
						aMobLevel.append(rs2.getInt("npc.level"))
						aMobAggro.append(rs2.getInt("npc.aggro"))
						aMobType.append(rs2.getString("npc.type"))
			con2.close()
			length = len(aMobID)
			maxPerPage = 10
			maxPages = int(length / maxPerPage)
			if length > maxPerPage * maxPages: maxPages = maxPages + 1
			if page > maxPages: page = maxPages
			start = maxPerPage * page
			end = length
			if (end - start) > maxPerPage: end = start + maxPerPage
			text += "<table width=260><tr>"
			if page == 0:
				text += "<td width=40><button value=\"Back\" action=\"bypass -h Quest 8003_Search\" width=40 height=15 back=\"L2UI_ct1.button_df\" fore=\"L2UI_ct1.button_df\"></td>"
			else :
				text += "<td width=40><button value=\"Back\" action=\"bypass -h Quest 8003_Search i "+ str(page-1) + " " + str(item_id) + "\" width=40 height=15 back=\"L2UI_ct1.button_df\" fore=\"L2UI_ct1.button_df\"></td>"
			text += "<td width=180><center><a action=\"bypass -h Quest 8003_Search\">Item/Material search Result</a></center></td>"
			if (page + 1) < maxPages:
				text += "<td width=40><button value=\"Next\" action=\"bypass -h Quest 8003_Search i "+ str(page+1) + " " + str(item_id) + "\" width=40 height=15 back=\"L2UI_ct1.button_df\" fore=\"L2UI_ct1.button_df\"></td>"
			else :
				text += "<td width=40></td>"
			text += "</tr></table>"
			text += "<center>Result for: "
			if icon <> "none":
				text +=	"<img src=\"" + icon + "\" width=32 height=32>"
			text += "<font color=\"LEVEL\">\"" + name + "\"</font><br1>"
			text += "Found:" + str(length) + " Page:" + str(page+1)+ "/" + str(maxPages) +"</center>"
			text += "<table width=260>"
			i = 0
			for i in range(start,end):
				text += "<tr>"
				text += "<td><a action=\"bypass -h Quest 8003_Search s 0 " + str(aMobID[i]) + "\">" + aMobName[i] + " " + str(aMobLevel[i])
				if aMobAggro > 0 :
					text += "*"
				if aMobType[i] == "L2Boss":
					text += "<font color=\"DD0000\"> Boss</font>"
				if aMobType[i] == "L2RaidBoss":
					text += "<font color=\"DD0000\"> RB</font>"
				text +="</td>"
				text += "<td><a action=\"bypass -h Quest 8003_Search d 0 " + str(aMobID[i]) + "\" width=40 height=15 back=\"L2UI_ct1.button_df\" fore=\"L2UI_ct1.button_df\">" + str(float(aChance[i]) / 10000 * Config.RATE_DROP_ITEMS) + "%</td>"
				if aCategory[i] == -1:
					text += "<font color=\"LEVEL\"> sw</font><br1>"
				text += "</td>"
				text += "</tr>"
			text += "</table>"
			text += "</body></html>"
			return text
		#search item name or part name
		if search_by == "search" :
			aItemID = []
			aItemName = []
			aItemIcon = []
			found = 0
			by_ID = 0
			if param.isdigit():
				item = int(param)
				by_ID = 1
			else:
				item = param
				if len(item) < 4: 
					message ("Please enter 4 ot more characters!")
					return htmltext
			for itemtype in (['armor','weapon','etcitem','custom_armor','custom_weapon','custom_etcitem']):
				if by_ID == 1:
					query = "select item_id, name from " + itemtype + " where item_id = " + str(item) + " LIMIT 1"
				else:
					query = "select item_id, name from " + itemtype + " where name LIKE '%" + str(item) + "%' ORDER BY item_id ASC LIMIT 100"
				con1=L2DatabaseFactory.getInstance().getConnection()
				stmt1=con1.prepareStatement(query)
				rs1=stmt1.executeQuery()
				if rs1 :
					while (rs1.next()):
							found = 1
							aItemID.append(rs1.getInt("item_id"))
							aItemName.append(rs1.getString("name"))
				con1.close()
			# HTML CODE
			text = title
			if found == 0:
				text += "Not found!"
			else :
				con2=L2DatabaseFactory.getInstance().getConnection()
				length=len(aItemID)		
				for i in range(0,length):
					query = "select icon from icons where item_id = " + str(int(aItemID[i])) + " LIMIT 1"
					stmt2=con2.prepareStatement(query)
					rs2=stmt2.executeQuery()
					if rs2.next():
						aItemIcon.append(rs2.getString("icon"))
					else:
						aItemIcon.append("none")
				con2.close()
				maxPerPage = 10
				maxPages = int(length / maxPerPage)
				if length > maxPerPage * maxPages: maxPages = maxPages + 1
				if page > maxPages: page = maxPages
				start = maxPerPage * page
				end = length
				if (end - start) > maxPerPage: end = start + maxPerPage
				text += "<table width=260><tr>"
				if page == 0:
					text += "<td width=40><button value=\"Back\" action=\"bypass -h Quest 8003_Search\" width=40 height=15 back=\"L2UI_ct1.button_df\" fore=\"L2UI_ct1.button_df\"></td>"
				else :
					text += "<td width=40><button value=\"Back\" action=\"bypass -h Quest 8003_Search search "+ str(page-1) + " " + str(item) + "\" width=40 height=15 back=\"L2UI_ct1.button_df\" fore=\"L2UI_ct1.button_df\"></td>"
				text += "<td width=180><center><a action=\"bypass -h Quest 8003_Search\">Item/Material search Result</a></center></td>"
				if (page + 1) < maxPages:
					text += "<td width=40><button value=\"Next\" action=\"bypass -h Quest 8003_Search search "+ str(page+1) + " " + str(item) + "\" width=40 height=15 back=\"L2UI_ct1.button_df\" fore=\"L2UI_ct1.button_df\"></td>"
				else :
					text += "<td width=40></td>"
				text += "</tr></table>"
				text += "<center>Result for: <font color=\"LEVEL\">\"" + str(item) + "\"</font><br1>"
				text += "Found:" + str(length) + " Page:" + str(page+1)+ "/" + str(maxPages) +"</center>"
				text += "<table width=260>"
				i = 0
				for i in range(start,end):
					text += "<tr>"
					text += "<td>"
					if str(aItemIcon[i]) <> "none":
						text +=	"<img src=\"" + str(aItemIcon[i]) + "\" width=32 height=32>"
					text += "</td>"
					text += "<td><a action=\"bypass -h Quest 8003_Search i 0 " + str(aItemID[i]) + "\">" + aItemName[i] + "</td>"
					text += "</tr>"
				text += "</table>"
			text += "</body></html>"
			return text
	# end of def onAdvEvent (self,event,npc,player)
		return htmltext

	def onTalk (Self,npc,player):
		npcId = npc.getNpcId()
		if npcId in NPC :
			htmltext = "search.htm"
		return htmltext

QUEST = Quest(8003,qn,"custom")

for i in NPC:
	QUEST.addStartNpc(i)
	QUEST.addTalkId(i)
